package code

import (
	"context"
	"fmt"
	"time"
)

func Context05() {
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(1*time.Second))
	defer cancel()
	stop := context.AfterFunc(ctx, func() {
		fmt.Println("after func")
	})
	// context.AfterFunc是一个完成或者取消后, 执行后返回一个stop函数, 用于停止parent context和func的关联
	// stop(): 返回true代表成功取消, false代表context已经完成
	// fmt.Println("task stop", stop())
	go task05(ctx, stop)
	time.Sleep(time.Second * 2)

}

func task05(ctx context.Context, stop func() bool) {
	select {
	case <-time.After(3 * time.Second):
		fmt.Println("done")
	case <-ctx.Done():
		fmt.Printf("task: context cancel or timeout:%v\n", ctx.Err())
		fmt.Println("task stop", stop())
	}

}
